package net.caixiaomi.info.ui.discovery;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sobot.chat.utils.ScreenUtils;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.LeagueCountryAdapter;
import net.caixiaomi.info.adapter.LeagueHomeAdapter;
import net.caixiaomi.info.adapter.LeagueHotAdapter;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.base.quickadapter.entity.MultiItemEntity;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.DIPlayerInfo;
import net.caixiaomi.info.model.DividerEntity;
import net.caixiaomi.info.model.LeagueCountryEntity;
import net.caixiaomi.info.model.LeagueGroupEntity;
import net.caixiaomi.info.model.LeagueInfoEntity;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.MatchFilterDialogFragment;
import net.caixiaomi.info.ui.view.DividerParser;
import net.caixiaomi.info.ui.view.DividerView;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.GridDivider;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;


import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;

/**
 * Created by mac on 2018/9/8.
 */

public class LeaguesHomeFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, OnRefreshListener {

    private LeagueHomeAdapter mGridViewAdapter0;
    private LeagueHomeAdapter mGridViewAdapterMain;
    private LeagueCountryAdapter mGridViewAdapter1;

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    private int mGroupId=-1;

    private View headerView;
    private String titleName;

    private boolean starts=false;
    private boolean firstLoad=true;

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        loadData();
    }

    @Override
    protected int fragmentLayout() {
        return R.layout.frag_common_list_divider;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        mListView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mGridViewAdapter0 = new LeagueHomeAdapter(R.layout.home_country_item_layout);
//        mListView.addItemDecoration(new GridDivider(getActivity(), ScreenUtils.dip2px(getActivity(),1)/2, this.getResources().getColor(R.color.blue)));
//        mListView.addItemDecoration(new GridDivider(getActivity(), ScreenUtils.dip2px(getActivity(),1)/2,  ContextCompat.getColor(getActivity(),R.color.light_gray)));

        mListView.setAdapter(mGridViewAdapter0);
        mRefresh.setOnRefreshListener(this);
        mRefresh.setBackgroundResource(R.color.white);


        if(mGroupId!=4){
            headerView=View.inflate(getActivity(),R.layout.league_home_header,null);
            TextView nameTv=headerView.findViewById(R.id.country_name);
            nameTv.setText(titleName+"赛事");
            mGridViewAdapter0.addHeaderView(headerView);
            mGridViewAdapter1=new LeagueCountryAdapter(R.layout.home_country_item_layout);
            RecyclerView listview1=headerView.findViewById(R.id.league_home_header_list);
            listview1.setLayoutManager(new GridLayoutManager(getActivity(), 3));
//            listview1.addItemDecoration(new GridDivider(getActivity(), ScreenUtils.dip2px(getActivity(),1)/2,  ContextCompat.getColor(getActivity(),R.color.blue)));
            listview1.setAdapter(mGridViewAdapter1);
        }

        View mainView=View.inflate(getActivity(),R.layout.league_home_list_layout,null);
        mGridViewAdapter0.addHeaderView(mainView);
        mGridViewAdapterMain=new LeagueHomeAdapter(R.layout.home_country_item_layout);
        RecyclerView listviewm=mainView.findViewById(R.id.league_home_content_list);
        listviewm.setLayoutManager(new GridLayoutManager(getActivity(), 3));
//        listviewm.addItemDecoration(new GridDivider(getActivity(), ScreenUtils.dip2px(getActivity(),1)/2,  ContextCompat.getColor(getActivity(),R.color.blue)));
        listviewm.setAdapter(mGridViewAdapterMain);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    public void initData(){

        if(mListView!=null) {
            mListView.scrollToPosition(0);
        }
        if(firstLoad){
            firstLoad=false;
            loadData();
        }
    }


    public void setGroupId(int id,String name){
        mGroupId=id;
        titleName=name;
        if(mListView!=null) {
            mListView.scrollToPosition(0);
        }

    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("groupId", mGroupId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<LeagueGroupEntity>> dis = requestService.getDiscoveryLeagues(params);
        dis.enqueue(new ResponseCallback<BaseCallModel<LeagueGroupEntity>>() {
            @Override
            public void onSuccess(BaseCallModel<LeagueGroupEntity> data) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                bindData(data.data);
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
            }
        });

    }

    private void bindData(final LeagueGroupEntity entity){
        try {
            initDivider0(entity);
            mGridViewAdapterMain.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    LeagueInfoEntity entity= (LeagueInfoEntity) adapter.getData().get(position);
                    if(entity.empty){
                        return;
                    }
                    Intent intent=new Intent(getActivity(),LeagueDetailActivity.class);
                    intent.putExtra("leagueId",entity.getLeagueId());
                    startActivity(intent);
                }
            });
            if(mGroupId!=4){
//                List<MultiItemEntity> list1=new ArrayList<>();
//                list1.addAll(entity.getContrys());
//                mGridViewAdapter1.setNewData(list1);

                initDivider1(entity);

                mGridViewAdapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        List<MatchItem> mMatchList=new ArrayList<>();
                        LeagueCountryEntity entity= (LeagueCountryEntity) adapter.getData().get(position);
                        if(entity.empty){
                            return;
                        }
                        for(int i=0;i<entity.getLeagueInfoList().size();i++){
                            MatchItem item=new MatchItem();
                            LeagueInfoEntity info=entity.getLeagueInfoList().get(i);
                            item.setLeagueAddr(info.getLeagueAddr());
                            item.setLeagueId(info.getLeagueId());
                            item.setLeagueName(info.getLeagueName());
                            item.setSelect(false);
                            mMatchList.add(item);
                        }
                        if (mMatchList.size()>0) {
                            String strData = JSON.toJSONString(mMatchList);
                            MatchFilterDialogFragment dialog = new MatchFilterDialogFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("data", strData);
                            bundle.putInt("planFilter", 0); //只看已购对阵去掉
                            bundle.putString("isAlreadyBuyMatch", "");
                            bundle.putInt("type",2);
                            bundle.putBoolean("only",true);
                            bundle.putString("groupId",mGroupId+"");
                            bundle.putString("title", entity.getContryName());
                            dialog.setArguments(bundle);
                            dialog.show(getFragmentManager(), MatchFilterDialogFragment.class.getName());
                        }
                    }
                });
            }
        }catch (Exception e){

        }
    }

    private void initDivider0(LeagueGroupEntity entity){
        List<LeagueInfoEntity> list0=entity.getGroupLeagues();
        for(int i=0;i<list0.size()%3;i++){
            LeagueInfoEntity ee=new LeagueInfoEntity();
            ee.empty=true;
            if(i==0) {
                ee.emptyAll = false;
            }
            list0.add(ee);
        }
        List<DividerEntity>divider0=new ArrayList<>();
        divider0.addAll(list0);
        new DividerParser().parseDivider(divider0,3);
        List<MultiItemEntity> listz=new ArrayList<>();
        listz.addAll(list0);
        mGridViewAdapterMain.setNewData(listz);
    }

    private void initDivider1(LeagueGroupEntity entity){
        List<LeagueCountryEntity> list0=entity.getContrys();
        for(int i=0;i<list0.size()%3;i++){
            LeagueCountryEntity ee=new LeagueCountryEntity();
            ee.empty=true;
            if(i==0) {
                ee.emptyAll = false;
            }
            list0.add(ee);
        }
        List<DividerEntity>divider0=new ArrayList<>();
        divider0.addAll(list0);
        new DividerParser().parseDivider(divider0,3);
        List<MultiItemEntity> listz=new ArrayList<>();
        listz.addAll(list0);
        mGridViewAdapter1.setNewData(listz);
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_FOOTBALL_MATCH_FILTER:
                    parseLeague(event.getMessage());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseLeague(String message){
        String leagueId="";
        try {
            org.json.JSONObject json=new org.json.JSONObject(message);
            JSONArray array=json.getJSONArray("data");
            String groupId=json.getString("groupId");
            if(!groupId.equals(mGroupId+"")){
                return;
            }
            for(int i=0;i<array.length();i++){
                org.json.JSONObject obj=array.getJSONObject(i);
                boolean select=obj.getBoolean("select");
                if(select){
                    leagueId=obj.getString("leagueId");
                    if(TextUtils.isEmpty(leagueId)){
                        return;
                    }
                    Intent intent=new Intent(getActivity(),LeagueDetailActivity.class);
                    intent.putExtra("leagueId",leagueId);
                    startActivity(intent);
                    break;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
